package com.codeoss.framework.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.UserContext;
import com.codeoss.framework.context.YunContext;
import com.codeoss.module.res.model.ResOrg;
import com.codeoss.module.res.model.ResRole;
import com.codeoss.module.res.model.ResUser;
import com.codeoss.module.res.service.IResOrgService;
import com.codeoss.module.res.service.IResRoleService;
import com.codeoss.module.res.service.IResUserService;

@Component
public class UserUtil {
	@Autowired
	private IResUserService resUserService;
	@Autowired
	private IResRoleService resRoleService;
	@Autowired
	private IResOrgService resOrgService;
	
	public void init(String username,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
	    YunContext yunContext=YunContext.getCurrentContext();
		
		QueryWrapper<ResUser> queryWrapper = new QueryWrapper<ResUser>();
		queryWrapper.eq("username", username);
		
		ResUser resUser=resUserService.getOne(queryWrapper);
		
		UserContext userContext=new UserContext();
		userContext.setResUserId(resUser.getId());
		userContext.setUsername(username);
		userContext.setResOrgId(resUser.getResOrgId());
		
		List<ResRole> roleList=resRoleService.getResRoleListByUserId(resUser.getId());
		List<String> roleCodeList=new ArrayList<String>();
		List<Long> roleIdList=new ArrayList<Long>();
		
		userContext.setRoleCodeList(roleCodeList);
		userContext.setRoleIdList(roleIdList);
		for(int i=0;i<roleList.size();i++) {
			roleCodeList.add(roleList.get(i).getCode());
			roleIdList.add(roleList.get(i).getId());
		}
		
		List<ResOrg> orgList=resOrgService.getResOrgListByRoleIdList(roleIdList);
		List<Long> orgIdList=new ArrayList<Long>();
		userContext.setOrgIdList(orgIdList);
		
		String accessOrgIds="(";
		for(int i=0;i<orgList.size();i++) {
			orgIdList.add(orgList.get(i).getId());
			if(i>0) {
				accessOrgIds+=",";
			}
			accessOrgIds+=orgList.get(i).getId();
		}
		accessOrgIds+=")";
		userContext.setAccessOrgIds(accessOrgIds);
		
		yunContext.setAttribute("_UserContext_", userContext);
	}
}
